package com.ybkj.o2o.zhuanxian.common;

import com.ybkj.o2o.zhuanxian.service.OrderService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class SerialNumber {

    private Map<String, AtomicLong> map = new ConcurrentHashMap<>();

    @Autowired
    private OrderService orderService;

    /**
     * 获取流水号 .
     *
     * @param appKey 区分系统
     */
    public synchronized String getSeqNo(String appKey) {

        AtomicLong atomicLong = map.get(appKey);

        long seq = 0;

        if (null == atomicLong) {
            long number = orderService.countForToday(appKey);
            atomicLong = new AtomicLong(number);
            map.put(appKey, atomicLong);
        }

        seq = atomicLong.incrementAndGet();

        String format = String.format("%04d", seq);
        Random random = new Random();
        int ran = 10 + (random.nextInt(89));
        return format + ran;
    }
}
